<template>
  <div class="user-list">
    <!-- 面包屑 -->
    <el-row>
      <my-breadcrumb level1="设备管理" level2="设备列表"></my-breadcrumb>
    </el-row>
    <!-- 搜索 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-input
          placeholder="请输入设备部分名称"
          v-model="query.device_name"
          @clear="getDeviceListData"
          @keyup.native.enter="getDeviceListData"
          clearable
          class="input-with-select"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getDeviceListData"
          ></el-button>
        </el-input>
      </el-col>
      <el-col :span="6">
        <el-select
          v-model="query.device_department_id"
          placeholder="请选择部门"
          @change="handleSelectChange"
        >
          <el-option
            v-for="item in departmentList"
            :key="item.id"
            :label="item.departname"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="3">
        <el-button
          type="success"
          icon="el-icon-circle-plus-outline"
          plain
          @click="dialogVisibleAdd = true"
          >添加设备</el-button
        >
      </el-col>
    </el-row>
    <!-- 分页 -->
    <el-row>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>
    <!-- 表格 -->
    <el-row>
      <el-table :data="tableData" style="width: 100%" size="mini" height="420">
        <el-table-column type="index" label="#" width="60"></el-table-column>
        <el-table-column prop="device_id" label="设备编号" width="100">
        </el-table-column>
        <el-table-column prop="device_name" label="设备名称" width="100">
        </el-table-column>
        <el-table-column prop="device_model" label="设备型号" width="100">
        </el-table-column>
        <el-table-column
          prop="device_manufacturer"
          label="生产厂家"
          width="200"
        >
        </el-table-column>
        <el-table-column
          prop="device_date_production"
          label="出厂日期"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.device_date_production | fmBaseDateStyle }}
          </template>
        </el-table-column>
        <el-table-column
          prop="device_date_service"
          label="投运日期"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.device_date_service | fmBaseDateStyle }}
          </template>
        </el-table-column>
        <el-table-column prop="device_data_update" label="更换日期" width="100">
          <template slot-scope="scope">
            {{ scope.row.device_data_update | fmBaseDateStyle }}
          </template>
        </el-table-column>
        <el-table-column prop="device_count" label="数量" width="60">
        </el-table-column>
        <el-table-column prop="device_type" label="设备类型" width="100">
        </el-table-column>
        <el-table-column prop="departname" label="所属部门" width="150">
        </el-table-column>
        <el-table-column prop="device_position" label="设备位置" width="100">
        </el-table-column>
        <el-table-column prop="device_status" label="运行状态" width="100">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.device_status === 0 ? 'success' : 'danger'"
              >{{ scope.row.device_status === 0 ? '正常' : '异常' }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="device_flaw" label="现存缺陷" width="150">
        </el-table-column>
        <el-table-column prop="device_suggest" label="处理建议" width="150">
        </el-table-column>
        <el-table-column prop="device_tips" label="备注" width="150">
        </el-table-column>
        <el-table-column prop="device_manager" label="责任人" width="100">
        </el-table-column>
        <el-table-column prop="id" label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-row>
              <el-tooltip effect="dark" content="编辑" placement="top">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  plain
                  size="mini"
                  @click="handleEdit(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除" placement="top">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  plain
                  size="mini"
                  @click="handleDelete(scope.row)"
                ></el-button>
              </el-tooltip>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <!-- excel 导出 -->
    <!-- excel 导入 -->

    <el-row>
      <el-col :span="2">
        <my-excel-export
          filename="2019安保设备信息表"
          :excelTableData="excelTableData"
        >
        </my-excel-export>
      </el-col>
      <el-col :offset="1" :span="2">
        <my-excel-import
          @excelSuccess="handelExcelSuccess"
          @excelError="handelExcelError"
        ></my-excel-import>
      </el-col>
    </el-row>
    <!-- 添加设备 -->
    <com-add
      :dialogVisibleAdd="dialogVisibleAdd"
      @addDialogClosed="dialogVisibleAdd = false"
      @addSuccess="getDeviceListData"
    ></com-add>
    <!-- 编辑设备 -->
    <com-edit
      :dialogVisibleEdit="dialogVisibleEdit"
      :currInfo="currInfo"
      @editDialogClosed="dialogVisibleEdit = false"
      @editSuccess="getDeviceListData"
    ></com-edit>
  </div>
</template>

<script>
import MyBreadcrumb from '@/components/MyBreadcrumb'
import MyExcelExport from '@/components/MyExcelExport'
import MyExcelImport from '@/components/MyExcelImport'

import ComAdd from '@/views/devices/components/ComAdd'
import ComEdit from '@/views/devices/components/ComEdit'

import { convertExcelData, checkNoneDepartment } from '@/plugins/utils'
import moment from 'moment'

export default {
  components: {
    MyBreadcrumb,
    ComAdd,
    ComEdit,
    MyExcelExport,
    MyExcelImport
  },
  data() {
    return {
      query: {
        device_name: '',
        device_department_id: 0
      },
      tableData: [],
      total: 0,
      pageSize: 5,
      pageNum: 1,
      dialogVisibleAdd: false,
      dialogVisibleEdit: false,
      currInfo: null,
      departmentList: []
    }
  },

  computed: {
    // 表格导出格式数据
    excelTableData() {
      const tempTableData = JSON.parse(JSON.stringify(this.tableData))
      tempTableData.forEach(element => {
        element.device_date_production = moment(
          element.device_date_production
        ).format('YYYY-MM-DD')
        element.device_date_service = moment(
          element.device_date_service
        ).format('YYYY-MM-DD')
        element.device_data_update = moment(element.device_data_update).format(
          'YYYY-MM-DD'
        )
      })

      return [
        {
          title: '2019安保设备信息表',
          tHeader: [
            '设备编号',
            '设备名称',
            '设备型号',
            '生产厂家',
            '出厂日期',
            '投运日期',
            '更换日期',
            '数量',
            '设备类型',
            '所属部门',
            '设备位置',
            '运行状态',
            '现存缺陷',
            '处理建议',
            '备注',
            '责任人'
          ],
          keys: [
            'device_id',
            'device_name',
            'device_model',
            'device_manufacturer',
            'device_date_production',
            'device_date_service',
            'device_data_update',
            'device_count',
            'device_type',
            'departname',
            'device_position',
            'device_status',
            'device_flaw',
            'device_suggest',
            'device_tips',
            'device_manager'
          ],
          table: tempTableData
        }
      ]
    }
  },
  created() {
    this.getDeviceListData()
    // 初始化获取所有部门数据，返回一个选择数组
    this.getDepartmentList()
  },
  methods: {
    async getDepartmentList() {
      const { data } = await this.$http.get('/department')
      this.departmentList = data.data.departmentList
      if (data.meta.status !== 200) {
        this.$message.warning(data.meta.msg)
      }

      this.departmentList.unshift({
        id: 0,
        departname: '所有部门'
      })
    },

    async getDeviceListData() {
      const { data } = await this.$http.get('/devices', {
        params: {
          query: this.query,
          pagenum: this.pageNum,
          pagesize: this.pageSize
        }
      })
      if (data.meta.status === 200) {
        const { total, deviceList } = data.data
        this.tableData = deviceList
        this.total = total
      } else {
        this.$message.warning(data.meta.msg)
      }
    },

    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageSize = val
      // 切换每页数据条目数量的时候，页码切回到 1
      this.pageNum = 1
      this.getDeviceListData()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.pageNum = val
      this.getDeviceListData()
    },

    // 删除按钮
    handleDelete(rowObj) {
      this.$confirm('此操作将删除该设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const {
            data: { meta }
          } = await this.$http.delete('/devices/' + rowObj.device_id)

          if (meta.status === 200) {
            this.$message.success(meta.msg)
            this.getDeviceListData()
          } else {
            this.$message.error(meta.msg)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑
    handleEdit(rowObj) {
      console.log(rowObj)
      this.dialogVisibleEdit = true
      this.currInfo = JSON.parse(JSON.stringify(rowObj))
    },
    // excel 导入成功事件
    async handelExcelSuccess(sourceData) {
      console.log(sourceData)

      // 导入表的列名字段对应关系
      const convertObj = {
        设备名称: 'device_name',
        设备型号: 'device_model',
        生产厂家: 'device_manufacturer',
        出厂日期: 'device_date_production',
        投运日期: 'device_date_service',
        更换日期: 'device_data_update',
        数量: 'device_count',
        设备类型: 'device_type',
        所属部门: 'departname',
        设备位置: 'device_position',
        运行状态: 'device_status',
        现存缺陷: 'device_flaw',
        处理建议: 'device_suggest',
        备注: 'device_tips',
        责任人: 'device_manager'
      }
      const list = convertExcelData(sourceData[0].data, convertObj)

      const { data: deparmentData } = await this.$http.get('/department')

      if (deparmentData.meta.status !== 200) {
        this.$message.warning(deparmentData.meta.msg)
      }

      const noneDepartmentList = checkNoneDepartment(
        list,
        deparmentData.data.departmentList
      )

      if (noneDepartmentList.length > 0) {
        this.$message.info(
          '以下部门尚未建立，无法导入设备数据：' + noneDepartmentList
        )
        return
      }

      const { data } = await this.$http.post('/devices/all', list)

      console.log(data)

      if (data.meta.status === 201) {
        // 导入成功多少条？

        this.$message.success(data.meta.msg)
      } else {
        this.$message.warning(data.meta.msg)
      }
    },
    // excel 导入失败事件
    handelExcelError(err) {
      console.log(err)
      this.$message.error('导入失败:' + err)
    },
    // 选择部门发生变化
    handleSelectChange() {
      this.getDeviceListData()
    }
  }
}
</script>

<style lang="less" scoped>
.user-list {
  .el-row {
    padding: 5px 0;
  }
}
</style>
